package com.zztl.infiniteBand.ui.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import android.text.TextUtils
import android.view.View
import butterknife.OnClick
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.yalantis.ucrop.UCrop
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpActivity
import com.zztl.infiniteBand.eventbus.UpdateHeaderEvent
import com.zztl.infiniteBand.model.PersonInfoBean
import com.zztl.infiniteBand.model.UploadFileBean
import com.zztl.infiniteBand.net.RetorfitServiceManger
import com.zztl.infiniteBand.net.imp.RequestKeys
import com.zztl.infiniteBand.presenter.PersenInfoPresenter
import com.zztl.infiniteBand.ui.view.CommonItemView
import com.zztl.infiniteBand.ui.view.dialog.PhotoPop
import com.zztl.infiniteBand.ui.view.mvpview.PersonInfoView
import com.zztl.infiniteBand.util.device.DeviceUtil
import com.zztl.infiniteBand.util.GlideCircleTransform
import com.zztl.infiniteBand.util.PermissionUtils
import kotlinx.android.synthetic.main.activity_person_info.*
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.IOException

class PersonInfoActivity : BaseMvpActivity<PersonInfoView, PersenInfoPresenter>(), PersonInfoView {


    lateinit var mPresenter: PersenInfoPresenter
    var nickname: String? = ""
    private var mPhotoPop: PhotoPop? = null
    private var mHeadPortraitFile: File? = null
    private var mCropedFile: File? = null
    private var mUri: Uri? = null
    private var mHeaderUrl: String? = null
    private val CAMERA = 10
    private val ALBUM = 20
    private val NICK_NAME = 30
    lateinit var photoList: List<String>


    private val mPermissionGrant = object : PermissionUtils.PermissionGrant {
        override fun onPermissionGranted(requestCode: Int) {
            when (requestCode) {
                PermissionUtils.CODE_MULTI_PERMISSION -> showPhotoPop()
            }
        }
    }


    override fun setLayoutId(): Int = R.layout.activity_person_info


    override fun initBase() {
        setTitle(getString(R.string.个人信息))
        photoList = listOf<String>(
                getString(R.string.拍照), getString(R.string.从相册中选取)
        )

        item_nick_name.setItemRightClickListener(object : CommonItemView.OnItemRightClickListener {
            override fun onClickItemRight(viewID: Int) {
                showActivityForResult(this@PersonInfoActivity, SetNickNameActivity::class.java, NICK_NAME)
            }
        })

        item_device.setItemRightClickListener(object : CommonItemView.OnItemRightClickListener {
            override fun onClickItemRight(viewID: Int) {
                if (DeviceUtil.getLastConnectMac().isNotEmpty()) showActivity(this@PersonInfoActivity, MyDeviceActivity::class.java)
            }
        })

        mPresenter.getUserInfo(this)


    }


    override fun onResume() {
        //        mWatchBeans = BraceletApplication.getmDaoSession().getBindedWatchBeanDao().loadAll();
        if (DeviceUtil.getLastConnectMac().isEmpty()) {
            item_device.rightTextStr = "0 " + getString(R.string.个设备)
            item_device.setRightImg2Visible(false)
        } else {
            item_device.setRightImg2Visible(true)
            item_device.rightTextStr = "1 " + getString(R.string.个设备)
        }


        super.onResume()
    }

    override fun createPresenter(): PersenInfoPresenter {
        mPresenter = PersenInfoPresenter()
        return mPresenter
    }

    @OnClick(R.id.item_header, R.id.item_nick_name, R.id.item_device)
    fun click(view: View) {
        when (view.id) {
            R.id.item_header -> PermissionUtils.requestMultiPermissions(this, mPermissionGrant, PermissionUtils.CODE_UPLOAD_IMG)
            R.id.item_nick_name -> {
                val intent = Intent(this, SetNickNameActivity::class.java)
                intent.putExtra("nickname", nickname)
                showActivityForResult(intent, NICK_NAME)
            }
            R.id.item_device -> {
                if (DeviceUtil.getLastConnectMac().isNotEmpty()) showActivity(this, MyDeviceActivity::class.java)
            }
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant)

    }


    private fun showPhotoPop() {
        if (mPhotoPop == null) {
            mPhotoPop = PhotoPop(this, object : PhotoPop.PopOnItemClickListener {
                override fun onItemClick(position: Int) {
                    mPhotoPop!!.dismiss()
                    val mHeadPortraitFileDir = File(Environment.getExternalStorageDirectory().absolutePath + "/gvc/Image")
                    if (!mHeadPortraitFileDir.exists()) {
                        mHeadPortraitFileDir.mkdirs()
                    }
                    mHeadPortraitFile = File(mHeadPortraitFileDir.absolutePath,
                            "/header.jpeg")
                    if (!mHeadPortraitFile!!.exists()) {
                        try {
                            mHeadPortraitFile!!.createNewFile()
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }

                    }

                    try {
                        if (position == 0) {

                            //拍照
                            val intent = Intent("android.media.action.IMAGE_CAPTURE")
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                val photoURI = FileProvider.getUriForFile(this@PersonInfoActivity,
                                        "com.zztl.infiniteBand.fileprovider",
                                        mHeadPortraitFile!!)
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                            } else {
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mHeadPortraitFile))
                            }
                            showActivityForResult(intent, CAMERA)
                        } else if (position == 1) {
                            //从相册中选择
                            val intent = Intent()
                            intent.type = "image/*"
                            intent.action = Intent.ACTION_GET_CONTENT
                            intent.addCategory(Intent.CATEGORY_OPENABLE)
                            showActivityForResult(Intent.createChooser(intent, "Select Picture"), ALBUM)
                            //                            showActivityForResult(intent,ALBUM);
                        }
                    } catch (e: Exception) {

                    }
                }
            }, 1, false).setData(photoList)
        }
        mPhotoPop!!.showPopupWindow()
    }


    public override fun onActivityResult(requestCode: Int, resultCode: Int, result: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            val options = UCrop.Options()
            options.setCompressionFormat(Bitmap.CompressFormat.JPEG)
            options.setCompressionQuality(100)
            if (requestCode == ALBUM) {
                UCrop.of(result!!.data!!, Uri.fromFile(mHeadPortraitFile))
                        .withAspectRatio(1f, 1f)
                        .withMaxResultSize(300, 300)
                        .withOptions(options)
                        .start(this)
            } else if (requestCode == CAMERA) {
                mCropedFile = File(this.cacheDir.absolutePath, "/cropped.jpeg")
                if (!mCropedFile!!.exists()) {
                    try {
                        mCropedFile!!.createNewFile()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }

                }
                UCrop.of(Uri.fromFile(mHeadPortraitFile), Uri.fromFile(mCropedFile))
                        .withAspectRatio(1f, 1f)
                        .withMaxResultSize(300, 300)
                        .withOptions(options)
                        .start(this)
            } else if (requestCode == UCrop.REQUEST_CROP) {
                mUri = UCrop.getOutput(result!!)
                mPresenter.updateMyPhoto(mUri, this)
            } else if (requestCode == NICK_NAME) {
                item_nick_name.rightTextStr = result!!.getStringExtra("name")
            }

        }

    }

    override fun getInfoSuccess(bean: PersonInfoBean) {
        bean.data!!.nickname?.let {
            nickname = if (it.isEmpty()) (if (bean.data?.realName!!.isEmpty()) bean.data?.phone else (bean.data?.realName)) else it
            item_nick_name.rightTextStr = nickname
        }

        item_account_num.rightTextStr = bean.data!!.email
        setHeaderImg(bean.data!!.imageUrl)
    }

    override fun loadSuccess(bean: UploadFileBean) {
        mHeaderUrl = bean.data!!.fileUrl
        mPresenter.updatePersonInfo(RequestKeys.IMGURL, RetorfitServiceManger.BASE_IMG_URL + mHeaderUrl!!, this)
    }

    override fun upDateSuccess(b: Boolean) {
        if (b) {
            if (null != mHeaderUrl) {
                setHeaderImg(RetorfitServiceManger.BASE_IMG_URL + mHeaderUrl!!)
                EventBus.getDefault().post(UpdateHeaderEvent(RetorfitServiceManger.BASE_IMG_URL + mHeaderUrl!!))
            }
        }
    }

    override fun loadFail() {

    }

    private fun setHeaderImg(imgUrl: String?) {
        if (TextUtils.isEmpty(imgUrl)) {
            return
        }
        Glide.with(this)
                .load(imgUrl)
                .apply(RequestOptions().placeholder(R.mipmap.ic_defaultphoto).transform(GlideCircleTransform(this)))
                .into(iv_header)
    }
}
